package no.ntnu.item.ttm4115.termproject.gpsagent;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedList;

import no.tellu.common.actorframe.ActorSM;
import no.ntnu.item.ttm4115.termproject.GpsCoords;


public class GpsAgentActions extends Object {
	public static void initialize(GpsAgentSM asm){
		// 
		System.out.println("init...");
		asm.startTimer(3000, "gpsReadInterval");
	}

	private static void readGpsData(GpsAgentSM asm){

		try {
			asm.inputStream = asm.serialPort.getInputStream();
		} catch (IOException e) {System.out.println(e);}

		asm.dataList = new LinkedList();
		byte[] readBuffer = new byte[5000];
		int pos = 0;
		try {
			// reading the data available at the inputstream
			while (asm.inputStream.available() > 0) {			
				byte[] srcBuffer = new byte[20];
				int numBytes = asm.inputStream.read(srcBuffer);		

				if(numBytes>0){
					//System.out.println("rb: "+ srcBuffer+" "+readBuffer+" "+ pos+" "+ numBytes);
					System.arraycopy(srcBuffer, 0, readBuffer, pos, numBytes);
				}

				pos = pos + numBytes;
			}
			// putting the data into the linked list
			asm.dataList.add(new String(readBuffer,0,pos));
		} catch (Exception e) {e.printStackTrace();}

		// populating the data as string..retrieving from linked list
		String data="";
		Iterator i = asm.dataList.iterator();
		while(i.hasNext()){
			data+=i.next();
		}

		// spliting the data into sentences (lines)
		String [] temp = data.split("\n");
		for(int j=0;j<temp.length;j++){
			String [] temprmc = temp[j].split(",");
			if(temp[j].contains("$GPRMC") && (temprmc.length>=7)) // to make sure that sufficient information is available
			{
				//System.out.println("parsed: "+ parseGPRMC(temp[j]));
				parseGPRMC(temp[j], asm);
			}
		}

	}

	// method to parse GPRMC string
	/* $GPRMC,004007,V,3748.410,N,12226.632,W,000.0,360.0,130102,015.7,E*6F */
	/* $GPRMC,time,V or A,ddmm.mmm,N or S,dddmm.mmm,W or E,000.0,360.0,130102,015.7,E*6F */
	private static String parseGPRMC(String data,GpsAgentSM asm )
	{
		//System.out.println("GPRMC String: "+ data);
		String computed = "";
		String lat = "", latSgn = "", lon = "", lonSgn = "";
		String nmeaKey = "";
		try { nmeaKey = data.substring(3, 6) ;}
		catch (Exception e)
		{ return ""; }
		if (nmeaKey.equals("RMC"))
		{	//System.out.println("key: "+ nmeaKey);
			/* $GPRMC,004007,V,3748.410,N,12226.632,W,000.0,360.0,130102,015.7,E*6F */
			if (data.indexOf(",V,") > -1)
			{  // That's what we're interested in.
				// Example : [$GPRMC,004007,A,3748.410,N,12226.632,W,000.0,360.0,130102,015.7,E*6F]
				String tmp = data.substring(data.indexOf(",V,") + ",V,".length());  
				// tmp is now : [3748.410,N,12226.632,W,000.0,360.0,130102,015.7,E*6F]
				if (tmp.indexOf(",") > -1) // Latitude Value
				{
					lat = tmp.substring(0, tmp.indexOf(","));
					tmp = tmp.substring(tmp.indexOf(",") + ",".length());
					// tmp is now : [N,12226.632,W,000.0,360.0,130102,015.7,E*6F]
				}
				if (tmp.indexOf(",") > -1) // Latitude Sign
				{
					latSgn = tmp.substring(0, tmp.indexOf(","));
					tmp = tmp.substring(tmp.indexOf(",") + ",".length());
					// tmp is now : [12226.632,W,000.0,360.0,130102,015.7,E*6F]
				}
				if (tmp.indexOf(",") > -1) // Longitude Value
				{
					lon = tmp.substring(0, tmp.indexOf(","));
					tmp = tmp.substring(tmp.indexOf(",") + ",".length());
					// tmp is now : [W,000.0,360.0,130102,015.7,E*6F]
				}
				if (tmp.indexOf(",") > -1) // Longitude Sign
				{
					lonSgn = tmp.substring(0, tmp.indexOf(","));
					tmp = tmp.substring(tmp.indexOf(",") + ",".length());
					// tmp is now : [000.0,360.0,130102,015.7,E*6F]
				}
			}
		}
		if (lat.length() > 0)
		{
			if (lat.indexOf(".") > -1)
			{
				String s = lat.substring(0, lat.indexOf("."));
				s = s.substring(0, s.length() - 2) + lat.substring(s.length() - 2);
				lat = s;
				asm.lati = (Double.parseDouble(lat));
				System.out.println(asm.lati);
			}
		}
		else
			lat = "Not Set";
		if (lon.length() > 0)
		{
			if (lon.indexOf(".") > -1)
			{
				String s = lon.substring(0, lon.indexOf("."));
				s = s.substring(0, s.length() - 2) + lon.substring(s.length() - 2);
				lon = s;
				
				asm.longi = (Double.parseDouble(lon));
				System.out.println(asm.longi);
			}
		}
		else
			lon = "Not Set";

		computed = latSgn + " " + lat + "/" + lonSgn + " " + lon;
		return computed;
	}

	public static void gpsTimeout(GpsAgentSM asm){
	    // 
			//read the gps data
			System.out.println("Reading GPS Data... and setting time out");
	
			readGpsData(asm);
			//set the time again
			asm.startTimer(3000, "gpsReadInterval");
	asm.sendMessage(new GpsCoords(asm.longi,asm.lati), asm.getContext().getParentAddress());
	}	
}
